const fs = require('fs');//?文件夹操作
const multer = require('multer')
const formidable = require('formidable');

let server=function(app,db){
//?Cookie查询
const View_Cookie = function (request, calka) {
    db.query('select * from login where UserCookie=\'' + request.cookies.DOM_Cookie + '\'', function (err, data) {
        calka(err, data)
    })
}

//?菜品图片接收
app.post('/addimg', function (request, response) {
    View_Cookie(request, function (err, data) {
        if (data[0]) {
            // ?创建formidable表单解析对象
            const form = new formidable.IncomingForm();
            //?更改文件地址
            form.uploadDir = __dirname + '/img'
            //?解析用户传递过来的Formdata对象
            form.parse(request, (err, fields, files) => {
                // ?修改文件名
                fs.rename(files.file.filepath, __dirname + '/img/' + fields.FoodID + '.' + files.file.mimetype.split('/')[1], function () {
                    db.query("update recipe  set  Samplefigure='./img/" + fields.FoodID + '.' + files.file.mimetype.split('/')[1] + '\'  where FoodID=\'' + fields.FoodID + '\'', function (err, data) {
                        if (err) console.error(err);
                        response.send({ "code": 0, "result": 'succese' })
                    })
                })
            });
        } else response.send({ "code": -1, "result": 'error' })
    })
})

var upload = multer();

//?保存用户图片
app.post('/picture', upload.single('file'), function (request, response) {
    // console.log(request.file);
    let { buffer, mimetype } = request.file;//?获取文件内容
    View_Cookie(request, function (err, data) {
        console.log(data);
        db.query('select * from user where UserID=' + data[0]['UserID'], function (err, data_) {
            let fileType = mimetype.split('/')[1];//?文件类型
            let fileName = data[0]['UserID'] + '.' + fileType;//?文件名
            fs.writeFile(`./picture/${fileName}`, buffer, (err) => {
                if (err) {
                    response.send({ err: 1, msg: "上传失败" })
                } else {
                    db.query('update user set Portrait=\'' + fileName + '\' where UserID=' + data[0]['UserID'], function (err, data) {
                        if (err) console.error(err);
                        response.send({ err: 0, msg: "上传成功" })
                    })
                }
            })
        })
    })
})
}
module.exports=server